package com.atguigu.classes.preconditions;

/**
 * @program: myIDEA
 * @description: 二分搜索法
 * @author: Mr.zjx
 * create: 2021-07-06-15-15
 **/
public class 二分搜索法 {
    public static void main(String[] args) {
        int[] arr = {1,3,5,7,9,11,13,15,17};
        //定义关键词
        int keyWord = 9;
        int min = 0;//最小索引
        int max = arr.length-1;//最大索引
        int mid ;//中间索引
        int index = -1;
        //折半
        while(min <= max){
            mid = (min+max)/2;
            if(keyWord > arr[mid]){
                min = mid + 1;
            }else if (keyWord < arr[mid]){
                max = mid - 1;
            }else {
                index = mid;
                break;
            }
        }
        System.out.println(index);
    }

}
